cmake_minimum_required(VERSION 3.10)

project(HttpServerProject LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# ---- 编译选项 ----
add_compile_options(-O2 -g -Wall -Wextra)

# ---- 公共：CGI 输出目录 ----
set(CGI_OUT_DIR ${CMAKE_SOURCE_DIR}/wwwroot/cgi_bin)
file(MAKE_DIRECTORY ${CGI_OUT_DIR})

# ================= http_server =================
add_executable(http_server
    main.cc
    # TODO: 后续追加 HttpServer.cpp / Protocol.cpp / Util.cpp ...
)
# target_link_libraries(http_server PRIVATE pthread) # 需要的话解开

# ================= test_cgi =================
add_executable(test_cgi ${CMAKE_SOURCE_DIR}/TestCgi.cc)
set_target_properties(test_cgi PROPERTIES
    RUNTIME_OUTPUT_DIRECTORY ${CGI_OUT_DIR}
)

# ================= mysql_conn（使用系统新库）=================
# 1) 找 mysql_config
find_program(MYSQL_CONFIG mysql_config)
if(NOT MYSQL_CONFIG)
  message(FATAL_ERROR "未找到 mysql_config，请先安装: sudo apt-get install -y libmysqlclient-dev")
endif()
message(STATUS "mysql_config: ${MYSQL_CONFIG}")

# 2) 取编译/链接参数
execute_process(COMMAND ${MYSQL_CONFIG} --cflags
                OUTPUT_VARIABLE MYSQL_CFLAGS
                OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND ${MYSQL_CONFIG} --libs
                OUTPUT_VARIABLE MYSQL_LIBS
                OUTPUT_STRIP_TRAILING_WHITESPACE)
separate_arguments(MYSQL_CFLAGS)
separate_arguments(MYSQL_LIBS)

# 3) 目标与属性
add_executable(mysql_conn ${CMAKE_SOURCE_DIR}/wwwroot/cgi_bin/mysql_conn.cc)
target_compile_options(mysql_conn PRIVATE ${MYSQL_CFLAGS})
target_link_libraries(mysql_conn PRIVATE ${MYSQL_LIBS})
set_target_properties(mysql_conn PROPERTIES
    RUNTIME_OUTPUT_DIRECTORY ${CGI_OUT_DIR}
    BUILD_RPATH "\$ORIGIN/lib"   # 运行时优先到 cgi_bin/lib 查库（可搬家）
)

# ================= 安装/发布 =================
# 发布根目录：output/
set(CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}/output")

# 可执行文件
install(TARGETS http_server RUNTIME DESTINATION .)
install(TARGETS test_cgi   RUNTIME DESTINATION wwwroot/cgi_bin)
install(TARGETS mysql_conn RUNTIME DESTINATION wwwroot/cgi_bin)

# 静态资源（整包 wwwroot）
install(DIRECTORY ${CMAKE_SOURCE_DIR}/wwwroot/
        DESTINATION wwwroot
        FILES_MATCHING PATTERN "*")

# 可选：把 libmysqlclient.so 一并拷入包（做“可搬家”运行）
execute_process(COMMAND ${MYSQL_CONFIG} --variable=pkglibdir
                OUTPUT_VARIABLE MYSQL_PKGLIBDIR
                OUTPUT_STRIP_TRAILING_WHITESPACE)
if(EXISTS "${MYSQL_PKGLIBDIR}")
  install(DIRECTORY ${MYSQL_PKGLIBDIR}/
          DESTINATION wwwroot/cgi_bin/lib
          FILES_MATCHING PATTERN "libmysqlclient.so*")
endif()

# 一键发布：确保三目标都会被构建，然后安装到 output/
add_custom_target(release
  DEPENDS http_server test_cgi mysql_conn
  COMMAND ${CMAKE_COMMAND} --install .
  COMMENT "Packaging runtime to ${CMAKE_SOURCE_DIR}/output/"
)
